﻿using DevExpress.ExpressApp.DC;
using System.ComponentModel;
using System.Xml.Linq;

namespace EasyXaf.LowCode.WorkflowEditors.Models.Activities;

[DomainComponent]
public abstract class BranchesActivity : Activity, IBranchesActivity
{
    [Browsable(false)]
    public bool IsCollapse
    {
        get => GetPropertyValue<bool>();
        set => SetPropertyValue(value);
    }

    [Browsable(false)]
    public ObjectCollection<IBranch> Branches { get; }

    ObjectCollection<IBranch> IBranchesActivity.Branches => Branches;

    public BranchesActivity(IWorkflow workflow, ISequence sequence)
        : base(workflow, sequence)
    {
        Branches = new ObjectCollection<IBranch>(this);
    }

    public override void OnCloned()
    {
        base.OnCloned();

        foreach (var branch in Branches)
        {
            branch.OnCloned();
        }
    }

    public override void WriteStateToXml(XElement element)
    {
        base.WriteStateToXml(element);

        SetXmlValue(element, nameof(IsCollapse), IsCollapse);
    }

    public override void ReadStateFromXml(XElement element)
    {
        base.ReadStateFromXml(element);

        IsCollapse = GetXmlValue<bool>(element, nameof(IsCollapse));
    }

    public override void WriteToXml(XElement element)
    {
        base.WriteToXml(element);

        if (Branches.Any())
        {
            var branchesElement = new XElement(nameof(Branches));
            element.Add(branchesElement);
            foreach (var branch in Branches)
            {
                var branchElement = new XElement(branch.GetType().Name);
                branch.WriteToXml(branchElement);
                branchesElement.Add(branchElement);
            }
        }
    }

    public override void ReadFromXml(XElement element)
    {
        base.ReadFromXml(element);

        if (element.Element(nameof(Branches)) is XElement branchesElement)
        {
            foreach (var branchElement in branchesElement.Elements())
            {
                Branches.Add(Workflow.CreateBranchFromXml(branchElement, this));
            }
        }
    }
}
